﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System.Xml;
using System.Text;

namespace DoAn
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        private enum Screen
        {
            Introduction,
            Menu,
            Main,
            Pause
        }
        Screen mCurrentScreen = Screen.Introduction;

        public const int VIEWWIDTH = 1100;
        public const int VIEWHEIGHT = 680;

        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        //Video gioi thieu
        Introduction introduction;

        //Menu
        Menu menu;

        //Map
        Map map;

        //MapWithCells
        static public MapWithCells mapwithcells;
        String strMap;

        int WidthMiniMap = 235;
        int HeighMiniMap = 145; 
        //Cells
        static public int nCols = 100;
        static public int nRows = 100;
        static public int CellWidth = 50;
        static public int CellHeight = 50;
        static public int WidthMap = nCols * CellWidth;
        static public int HeighMap = nRows * CellHeight;
        static public Vector2[,] a;
        static public bool[,] b;

        //Profile
        Texture2D TextureProfile;
        Texture2D TextureAttack;
        Texture2D TextureBuild;
        Texture2D TextureDamageArmor;
        Texture2D TextureMove;
        Texture2D TextureRealTime;
        Texture2D TextureLocal;
        Texture2D TextureMiniMap;

        //Mouse cursor
        Texture2D TextureCursor;
        Texture2D TextureCursorAttack;
        Texture2D TextureCursorTarget;
        bool bTarget = false;
        int sizeTarget;
        static public Vector2 vectorTarget = new Vector2();
        Color cl = Color.White;

        //Khai báo Soldier
        Soldier soldier;

        //Khai báo Magic
        Magic magic;

        //Khai báo Đối thủ
        Soldier Deadman;

        //Khai báo Mouse, Keyboard
        MouseState mState;
        MouseState Pre_mState;
        KeyboardState kbState;
        bool Drag = false;

        //Nhóm Army đang được focus
        Army armyFocus;
        Rectangle rectFocus;
        Texture2D textureCircle;//Vòng tròn focus

        //Flag tấn công
        bool AClick = false;
        bool Aflag = false;

        //Sản xuất army
        bool RClick = false;
        bool TClick = false;
        bool MClick = false;
        bool SClick = false;
        bool EnterClick = false;
        bool EscClick = false;

        //RightClick
        bool bRightClick = false;
        //LeftClick
        bool bLeftClick = false;

        //Building
        static public MainHome mainhome;//Barrack
        static public MainHome deadhome;//Barrack
        GoldBuilding goldbuilding;//nhà vàng
        bool bGold = false;//Click chọn mua nhà vàng

        //Init
        static public Object init;

        SpriteFont theFont;
        SpriteFont theFont2;
        SpriteFont theFont3;
        Color colorLevel = Color.Blue;


        //Khai báo các Sprite và Icon đại diện trong profile
        Texture2D textureTextbox;
        Texture2D textureIconHero;
        Texture2D textureIconMagic;
        Texture2D textureIconGold;
        Texture2D textureIconGoldVirtual;
        MySprite spriteIcon;
        MySprite spriteIconMagic;
        MySprite spriteIconHero;
        MySprite spriteIconBarrack;
        MySprite spriteIconGoldBuilding;
        MySprite spriteicon;

        ////Sprite địa hình
        //public static MySprite[] DiaHinh;

        //biến đếm real time
        int realtime = 0;
        static public int gold = 1500;
        int thongbao;
        int timeThongbao;

        //Tùy chọn
        public static int Do_Kho = -1;//level
        int _imap = 0;//Chọn map
        int _iskin = 0;
        public static Color skin = Color.Red; //Chọn skin

        //Sound
        Song song;
        bool doingsound = true;

        //Textbox
        String strText = "";
        bool texting = true;

        //Pause Game
        bool bPause;

        //Keyboard
        KeyboardState oldKeyboardState, currentKeyboardState;

        string strPlayerName = "";

        //ket thuc
        bool bKetthuc = false;

        
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            IsMouseVisible = true;
            this.graphics.PreferredBackBufferWidth = VIEWWIDTH;
            this.graphics.PreferredBackBufferHeight = VIEWHEIGHT;

            //graphics.IsFullScreen = true;
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            menu = new Menu();

            menu.easy += new Menu.LevelHandler(menu_easy);
            menu.normal += new Menu.LevelHandler(menu_normal);
            menu.hard += new Menu.LevelHandler(menu_hard);

            menu.onSound +=new Menu.SoundHandler(menu_onSound);
            menu.offSound +=new Menu.SoundHandler(menu_offSound);
            
            menu.quitmsn +=new Menu.PlayingHandler(menu_quitmission);

            mState = Mouse.GetState();
            
            bPause = false;

            //tao danh sach Highscore
            creatXMLfile();

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here

            //Khoi tao Introduction
            introduction = new Introduction(Content, "Introduction/video");

            //Khoi tao Menu
            menu.LoadContent(Content);

            //Cells
            a = new Vector2[nRows, nCols];
            b = new bool[nRows, nCols];
            for (int i = 0; i < nRows; i++)
            {
                int y = i * CellHeight + CellHeight / 2;
                for (int j = 0; j < nCols; j++)
                {
                    int x = j * CellWidth + CellWidth / 2;
                    a[i, j] = new Vector2(x, y);
                    b[i, j] = false;
                }
            }

            //Map
            //map = new Map(Content, "Map//roadfork", new Vector2(5, 5), new Vector2(2000, 1600));
            
            //MapWithCells
            _imap = 1;
            strMap = "Map//snow";
            TextureMiniMap = Content.Load<Texture2D>("Map//snow");
            if (_imap == 1)
            {
                strMap = "Map//sand";
                TextureMiniMap = Content.Load<Texture2D>("Map//sand");
            }
            mapwithcells = new MapWithCells(Content, strMap, nCols, nRows, new Vector2(0, 0), CellWidth, CellHeight);

            //Chọn màu skin
            _iskin = 0;
            if(_iskin == 1)
                skin = Color.Green;



            //Profile
            textureTextbox = Content.Load<Texture2D>("images//others//chat");
            TextureProfile = Content.Load<Texture2D>("images//Profile//ProfileEmpty");
            TextureAttack = Content.Load<Texture2D>("images//Profile//Attack"); 
            TextureBuild = Content.Load<Texture2D>("images//Profile//build"); 
            TextureDamageArmor = Content.Load<Texture2D>("images//Profile//Damage_Armor");
            TextureRealTime = Content.Load<Texture2D>("images//Profile//realtime");
            TextureLocal = Content.Load<Texture2D>("images//others//local");
            //Khởi tạo các Sprite và icon đại diện trong profile
            textureIconHero = Content.Load<Texture2D>("images//Icon//iconHero");
            textureIconMagic = Content.Load<Texture2D>("images//Icon//iconMagic");
            textureIconGold = Content.Load<Texture2D>("images//House//goldbuilding1");
            textureIconGoldVirtual = Content.Load<Texture2D>("images//House//goldbuilding_virtual");
            spriteIconMagic = new MySprite(Content, "images//Icon//iconMagic//m", 8, new Vector2(VIEWWIDTH / 3 - 55, VIEWHEIGHT - 100), new Vector2(70, 65), 6);
            spriteIconHero = new MySprite(Content, "images//Icon//iconHero//h", 8, new Vector2(VIEWWIDTH / 3 - 90, VIEWHEIGHT - 105), new Vector2(140, 65), 6);
            spriteIconBarrack = new MySprite(Content, "images//House//barrack", 1, new Vector2(VIEWWIDTH / 3 - 55, VIEWHEIGHT - 109), new Vector2(80, 80), 6);
            spriteIconGoldBuilding = new MySprite(Content, "images//House//goldbuilding", 1, new Vector2(VIEWWIDTH / 3 - 55, VIEWHEIGHT - 109), new Vector2(80, 80), 6);
            spriteIcon = spriteIconMagic;

            ////Khởi tạo các Sprite địa hình
            //DiaHinh = new MySprite[12];
            //DiaHinh[0] = new MySprite(Content, "Map//water", mapwithcells.Topleft + new Vector2(20 * CellWidth, 10 * CellHeight), new Vector2(20 * CellWidth, CellHeight), 2);
            //DiaHinh[1] = new MySprite(Content, "Map//water", mapwithcells.Topleft + new Vector2(60 * CellWidth, 10 * CellHeight), new Vector2(20 * CellWidth, CellHeight), 1);
            //DiaHinh[2] = new MySprite(Content, "Map//water", mapwithcells.Topleft + new Vector2(20 * CellWidth, 90 * CellHeight), new Vector2(20 * CellWidth, CellHeight), 1);
            //DiaHinh[3] = new MySprite(Content, "Map//water", mapwithcells.Topleft + new Vector2(60 * CellWidth, 90 * CellHeight), new Vector2(20 * CellWidth, CellHeight), 1);
            //DiaHinh[4] = new MySprite(Content, "Map//water", mapwithcells.Topleft + new Vector2(40 * CellWidth, 30 * CellHeight), new Vector2(20 * CellWidth, CellHeight), 1);
            //DiaHinh[5] = new MySprite(Content, "Map//water", mapwithcells.Topleft + new Vector2(40 * CellWidth, 70 * CellHeight), new Vector2(20 * CellWidth, CellHeight), 1);
            //DiaHinh[6] = new MySprite(Content, "Map//water", mapwithcells.Topleft + new Vector2(10 * CellWidth, 20 * CellHeight), new Vector2(CellWidth, 20 * CellHeight), 1);
            //DiaHinh[7] = new MySprite(Content, "Map//water", mapwithcells.Topleft + new Vector2(10 * CellWidth, 60 * CellHeight), new Vector2(CellWidth, 20 * CellHeight), 1);
            //DiaHinh[8] = new MySprite(Content, "Map//water", mapwithcells.Topleft + new Vector2(90 * CellWidth, 20 * CellHeight), new Vector2(CellWidth, 20 * CellHeight), 1);
            //DiaHinh[9] = new MySprite(Content, "Map//water", mapwithcells.Topleft + new Vector2(90 * CellWidth, 60 * CellHeight), new Vector2(CellWidth, 20 * CellHeight), 1);
            //DiaHinh[10] = new MySprite(Content, "Map//water", mapwithcells.Topleft + new Vector2(30 * CellWidth, 40 * CellHeight), new Vector2(CellWidth, 20 * CellHeight), 1);
            //DiaHinh[11] = new MySprite(Content, "Map//water", mapwithcells.Topleft + new Vector2(70 * CellWidth, 40 * CellHeight), new Vector2(CellWidth, 20 * CellHeight), 1);
            
            //Mouse cursor
            TextureCursor = Content.Load<Texture2D>("images//Mouse//cursor");
            TextureCursorAttack = Content.Load<Texture2D>("images//Mouse//cursorAttack");
            TextureCursorTarget = Content.Load<Texture2D>("images//Mouse//target");

            

            //Vòng tròn focus
            textureCircle = Content.Load<Texture2D>("images//others//circle");

            //Init
            init = new Object();

            //khởi tạo MainHome
            mainhome = new MainHome(Content, "images\\House\\barrack", 1, new Vector2(), new Vector2(CellWidth * 3, CellHeight * 3), 6, 3000, 18, 0, 1, 1);
            mainhome.newBuilding(new Vector2(MapWithCells.WIDTHMAP / 2 - 75, MapWithCells.HEIGHTMAP / 2 - 75), init);//Thêm 1 MainHome

            deadhome = new MainHome(Content, "images\\House\\barrack", 1, new Vector2(), new Vector2(CellWidth * 3, CellHeight * 3), 6, 3000, 18, 0, 0, 1);
            deadhome.newBuilding(new Vector2(mapwithcells.Topleft.X + MapWithCells.WIDTHMAP / 2, mapwithcells.Topleft.Y + 50), init);//Thêm 1 MainHome
            deadhome.newBuilding(new Vector2(mapwithcells.Topleft.X + MapWithCells.WIDTHMAP - 200, mapwithcells.Topleft.Y + MapWithCells.HEIGHTMAP / 2), init);//Thêm 1 MainHome
            deadhome.newBuilding(new Vector2(mapwithcells.Topleft.X + MapWithCells.WIDTHMAP / 2, mapwithcells.Topleft.Y + MapWithCells.HEIGHTMAP - 200), init);//Thêm 1 MainHome
            deadhome.newBuilding(new Vector2(mapwithcells.Topleft.X + 50, mapwithcells.Topleft.Y + MapWithCells.HEIGHTMAP / 2), init);//Thêm 1 MainHome

            //khởi tạo GoldBuilding
            goldbuilding = new GoldBuilding(Content, "images\\House\\goldbuilding", 1, new Vector2(), new Vector2(CellWidth * 2, CellHeight * 2), 6, 3000, 12, 0, 1, 1);
            goldbuilding.newBuilding(new Vector2(MapWithCells.WIDTHMAP / 2 + 225, MapWithCells.HEIGHTMAP / 2 - 25), init);//Thêm 1 gold

            //khởi tạo Soldier
            soldier = new Soldier(Content, "images\\Hero\\23-", 256, new Vector2(300, 300), new Vector2(50, 50), 6, 300, 2, 20, 1, 4);
            mainhome.CreateHero(soldier, mainhome.mySprites[0]);//Thêm 1 soldier
            
            ////khởi tạo Deadman
            //if(Do_Kho != -1)
            //    switch (Do_Kho)
            //    {
            //        case 0: Deadman = new Soldier(Content, "images\\Hero\\23-", 256, new Vector2(300, 300), new Vector2(50, 50), 6, 250, 2, 20, 0, 4); break;
            //        case 1: Deadman = new Soldier(Content, "images\\Hero\\23-", 256, new Vector2(300, 300), new Vector2(50, 50), 6, 300, 2, 20, 0, 4); break;
            //        case 2: Deadman = new Soldier(Content, "images\\Hero\\23-", 256, new Vector2(300, 300), new Vector2(50, 50), 6, 350, 2, 20, 0, 4); break;
            //    }

            //khởi tạo magic
            magic = new Magic(Content, "images\\Magic\\34-", 64, new Vector2(300, 300), new Vector2(35, 50), 6, 150, 2, 5, 1, 1);

            //khởi tạo ArmyFocus
            armyFocus = new Army();

            //Bắt đầu vào fucus MainHome
            spriteicon = mainhome.mySprites[0];
            SearchByIcon();

            //Sound
            //song = Content.Load<Song>("Sound//Anh Cung Nho Em - Luong Bang Quang");
            song = Content.Load<Song>("Sound//background");

            theFont = Content.Load<SpriteFont>("SpriteFont1");
            theFont2 = Content.Load<SpriteFont>("SpriteFont2");
            theFont3 = Content.Load<SpriteFont>("SpriteFont3");
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here

            //khởi tạo Mouse, Keyboard;
            mState = Mouse.GetState();
            kbState = Keyboard.GetState();

            switch(mCurrentScreen)
            {
                case Screen.Introduction:
                    introduction.Update(gameTime);
                    if (kbState.IsKeyDown(Keys.P))
                    {
                        introduction.Stop();
                        mCurrentScreen = Screen.Menu;

                    }
                    break;
                case Screen.Menu:
                    {
                        menu.Update(this, gameTime);
                        //khởi tạo Deadman
                        if (Do_Kho != -1)
                        {
                            switch (Do_Kho)
                            {
                                case 0: Deadman = new Soldier(Content, "images\\Hero\\23-", 256, new Vector2(300, 300), new Vector2(50, 50), 6, 250, 2, 20, 0, 4); break;
                                case 1: Deadman = new Soldier(Content, "images\\Hero\\23-", 256, new Vector2(300, 300), new Vector2(50, 50), 6, 300, 2, 20, 0, 4); break;
                                case 2: Deadman = new Soldier(Content, "images\\Hero\\23-", 256, new Vector2(300, 300), new Vector2(50, 50), 6, 350, 2, 20, 0, 4); break;
                            }

                            if (menu.StrPlayerName.Contains("Enter"))
                                strPlayerName = menu.StrPlayerName.Remove(menu.StrPlayerName.Length - 5, 5);
                        }

                        break;
                    }
                case Screen.Main:
                    {
                        KeyboardState newState = Keyboard.GetState();
                        if (!bPause)
                        {
                            realtime++;//real time

                            if (MediaPlayer.State == MediaState.Stopped && doingsound)
                            {
                                MediaPlayer.Play(song);
                            }
                            if (kbState.IsKeyDown(Keys.S) && !texting)
                            {
                                SClick = true;
                            }
                            if (kbState.IsKeyUp(Keys.S) && !texting)
                            {
                                if (SClick)
                                {
                                    if (!doingsound)
                                    {
                                        MediaPlayer.Play(song);
                                        doingsound = true;
                                    }
                                    else
                                    {
                                        MediaPlayer.Stop();
                                        doingsound = false;
                                    }
                                }
                                SClick = false;
                            }

                            //Texting
                            if (kbState.IsKeyDown(Keys.Enter))
                            {
                                EnterClick = true;
                            }
                            if (kbState.IsKeyUp(Keys.Enter))
                            {
                                if (EnterClick)
                                {
                                    if (texting)
                                    {
                                        //strText = strText.Remove(strText.Length - 5, 5);
                                        texting = false;
                                        if (strText.ToLower().Equals("show me a hero 10"))
                                            soldier.newArmy(init, mainhome.mySprites[0], 10);
                                        if (strText.ToLower().Equals("show me a hero 9"))
                                            soldier.newArmy(init, mainhome.mySprites[0], 9);
                                        if (strText.ToLower().Equals("show me a hero 8"))
                                            soldier.newArmy(init, mainhome.mySprites[0], 8);
                                        if (strText.ToLower().Equals("show me a hero 7"))
                                            soldier.newArmy(init, mainhome.mySprites[0], 7);
                                        if (strText.ToLower().Equals("show me a hero 6"))
                                            soldier.newArmy(init, mainhome.mySprites[0], 6);
                                        if (strText.ToLower().Equals("show me a hero 5"))
                                            soldier.newArmy(init, mainhome.mySprites[0], 5);
                                        if (strText.ToLower().Equals("show me a hero 4"))
                                            soldier.newArmy(init, mainhome.mySprites[0], 4);
                                        if (strText.ToLower().Equals("show me a hero 3"))
                                            soldier.newArmy(init, mainhome.mySprites[0], 3);
                                        if (strText.ToLower().Equals("show me a hero 2"))
                                            soldier.newArmy(init, mainhome.mySprites[0], 2);
                                        if (strText.ToLower().Equals("show me a hero 1"))
                                            soldier.newArmy(init, mainhome.mySprites[0], 1);

                                        if (strText.ToLower().Equals("show me a magic 10"))
                                            magic.newArmy(init, mainhome.mySprites[0], 10);
                                        if (strText.ToLower().Equals("show me a magic 9"))
                                            magic.newArmy(init, mainhome.mySprites[0], 9);
                                        if (strText.ToLower().Equals("show me a magic 8"))
                                            magic.newArmy(init, mainhome.mySprites[0], 8);
                                        if (strText.ToLower().Equals("show me a magic 7"))
                                            magic.newArmy(init, mainhome.mySprites[0], 7);
                                        if (strText.ToLower().Equals("show me a magic 6"))
                                            magic.newArmy(init, mainhome.mySprites[0], 6);
                                        if (strText.ToLower().Equals("show me a magic 5"))
                                            magic.newArmy(init, mainhome.mySprites[0], 5);
                                        if (strText.ToLower().Equals("show me a magic 4"))
                                            magic.newArmy(init, mainhome.mySprites[0], 4);
                                        if (strText.ToLower().Equals("show me a magic 3"))
                                            magic.newArmy(init, mainhome.mySprites[0], 3);
                                        if (strText.ToLower().Equals("show me a magic 2"))
                                            magic.newArmy(init, mainhome.mySprites[0], 2);
                                        if (strText.ToLower().Equals("show me a magic 1"))
                                            magic.newArmy(init, mainhome.mySprites[0], 1);

                                        //Âm thanh
                                        if (strText.ToLower().Equals("sound on"))
                                        {
                                            MediaPlayer.Stop();
                                            MediaPlayer.Play(song);
                                            doingsound = true;
                                        }
                                        if (strText.ToLower().Equals("sound off"))
                                        {
                                            MediaPlayer.Stop();
                                            doingsound = false;
                                        }

                                        //Tiền
                                        if (strText.ToLower().Equals("show me the money"))
                                            gold = 100000;

                                        //Background
                                        if (strText.ToLower().Equals("background sand"))
                                        {
                                            mapwithcells = new MapWithCells(Content, "Map//sand", nCols, nRows, mapwithcells.Topleft, CellWidth, CellHeight);
                                            TextureMiniMap = Content.Load<Texture2D>("Map//sand");
                                        }
                                        if (strText.ToLower().Equals("background snow"))
                                        {
                                            mapwithcells = new MapWithCells(Content, "Map//snow", nCols, nRows, mapwithcells.Topleft, CellWidth, CellHeight);
                                            TextureMiniMap = Content.Load<Texture2D>("Map//snow");
                                        }

                                        //Win
                                        if (strText.ToLower().Equals("i win"))
                                        {
                                            deadhome.nSprites = 0;
                                        }
                                    }
                                    else
                                    {
                                        texting = true;
                                        strText = "";
                                    }
                                }
                                EnterClick = false;
                            }


                            //Typing
                            oldKeyboardState = currentKeyboardState;
                            currentKeyboardState = Keyboard.GetState();
                            Keys[] pressedKeys;
                            pressedKeys = currentKeyboardState.GetPressedKeys();

                            foreach (Keys key in pressedKeys)
                            {
                                if (oldKeyboardState.IsKeyUp(key))
                                {
                                    if (key == Keys.Back) // overflows
                                    {
                                        if (strText.Length > 0)
                                            strText = strText.Remove(strText.Length - 1, 1);
                                    }
                                    else
                                        if (key == Keys.Space)
                                            strText = strText.Insert(strText.Length, " ");
                                        else
                                        {
                                            switch (key)
                                            {
                                                case Keys.D0: strText += (0).ToString(); break;
                                                case Keys.D1: strText += (1).ToString(); break;
                                                case Keys.D2: strText += (2).ToString(); break;
                                                case Keys.D3: strText += (3).ToString(); break;
                                                case Keys.D4: strText += (4).ToString(); break;
                                                case Keys.D5: strText += (5).ToString(); break;
                                                case Keys.D6: strText += (6).ToString(); break;
                                                case Keys.D7: strText += (7).ToString(); break;
                                                case Keys.D8: strText += (8).ToString(); break;
                                                case Keys.D9: strText += (9).ToString(); break;
                                                default: strText += key.ToString(); break;
                                            }
                                        }
                                }
                            }

                            //currentKeyboardState = Keyboard.GetState();
                            //Keys[] key = currentKeyboardState.GetPressedKeys();
                            //strText += key.ToString();

                            //Tự động tạo deadman
                            Tu_Dong_Ra_Linh(Do_Kho);

                            //Map

                            //map.ScrollMap(kbState, VIEWWIDTH, VIEWHEIGHT);
                            //mapwithcells.ScrollMap(mState, VIEWWIDTH, VIEWHEIGHT);
                            mapwithcells.ScrollMap(kbState, VIEWWIDTH, VIEWHEIGHT);





                            if (kbState.IsKeyDown(Keys.A) && !texting)
                            {
                                if (armyFocus.nSprites > 0)
                                {
                                    AClick = true;
                                    cl = Color.Red;
                                }
                            }

                            //Xử lý Focus
                            if (mState.LeftButton == ButtonState.Pressed)
                            {
                                if (mState.Y <= 535)//nếu click trong vùng màn hình (phía bên trên profile)
                                {
                                    if (bGold)//Nếu chuẩn bị mua nhà vàng
                                    {
                                        Vector2 v = new Vector2(mState.X - CellWidth + 10, mState.Y - CellHeight + 10);
                                        if (!TestVector(v) && !TestVector(v + new Vector2(CellWidth, 0)) && !TestVector(v + new Vector2(0, CellHeight))
                                            && !TestVector(v + new Vector2(CellWidth, CellHeight)))
                                        {
                                            goldbuilding.newBuilding(v, init);
                                            bGold = false;
                                        }
                                    }
                                    else
                                    {
                                        //Chọn Target Tấn Công
                                        if (AClick)
                                        {
                                            if (!bLeftClick)
                                            {
                                                for (int i = 0; i < armyFocus.nSprites; i++)
                                                {
                                                    //Vector2 v = center(new Vector2(mState.X, mState.Y));
                                                    armyFocus.mySprites[i].Target = new Vector2(mState.X, mState.Y);
                                                    //cho b[i, j] = false => ô [i,j] không có ai đứng
                                                    uncheckCell(armyFocus.mySprites[i].PosCenter);
                                                    armyFocus.mySprites[i].FlagAttack = true;
                                                    Aflag = true;
                                                }
                                                DefinedTarget(ref bLeftClick);
                                            }
                                        }
                                        else
                                            if (!Drag)
                                            {
                                                Pre_mState = mState;
                                                int n = armyFocus.nSprites;
                                                armyFocus.mySprites.RemoveRange(0, n);
                                                armyFocus.nSprites = 0;
                                                Drag = true;
                                            }
                                    }
                                }
                                else
                                {
                                    if (mState.X > 13 && mState.X < 244 && mState.Y > 532 && mState.Y < 672)
                                    {
                                        SearchMiniMap();
                                    }
                                    else
                                    {
                                        if (!bLeftClick)
                                        {
                                            if (spriteIcon == spriteIconBarrack)
                                            {
                                                XulyProfileBarrack(new Vector2(mState.X, mState.Y));
                                            }
                                            else
                                            {
                                                if (spriteIcon == spriteIconHero || spriteIcon == spriteIconMagic)
                                                {
                                                    XulyProfileSoldier(new Vector2(mState.X, mState.Y));
                                                }
                                                else
                                                {
                                                    if (spriteIcon == spriteIconGoldBuilding)
                                                    {
                                                        XulyProfileGoldBuilding(new Vector2(mState.X, mState.Y));
                                                    }
                                                }
                                            }
                                            bLeftClick = true;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (!AClick)//Nếu không đang trong tình trạng chuẩn bị tấn công (bật cờ flagAttack)
                                {
                                    if (Drag)
                                    {
                                        int n = init.nSprites;
                                        Army af = new Army();
                                        for (int i = 0; i < n; i++)
                                        {
                                            if (init.mySprites[i].IsFocus(rectFocus))
                                            {
                                                //soldier.mySprites[i].Dynamic(2, 5);
                                                af.mySprites.Add(init.mySprites[i]);
                                                af.nSprites++;
                                            }
                                        }
                                        bool ta = false;
                                        for (int i = 0; i < af.nSprites; i++)
                                        {
                                            if (af.mySprites[i].Flag == 1)
                                            {
                                                ta = true;
                                                break;
                                            }
                                        }
                                        if (ta)
                                        {
                                            for (int i = 0; i < af.nSprites; i++)
                                            {
                                                if (af.mySprites[i].Flag == 1)
                                                {
                                                    armyFocus.mySprites.Add(af.mySprites[i]);
                                                    armyFocus.nSprites++;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            for (int i = 0; i < af.nSprites; i++)
                                            {
                                                armyFocus.mySprites.Add(af.mySprites[i]);
                                                armyFocus.nSprites++;
                                            }

                                        }
                                    }
                                    Drag = false;
                                }
                                else
                                {
                                    if (Aflag)
                                    {
                                        AClick = false;
                                        Aflag = false;
                                    }
                                }
                                bLeftClick = false;
                            }
                            if (Drag)
                            {
                                //tạo vùng chữ nhật focus
                                rectFocus = CreateRect(new Vector2(Pre_mState.X, Pre_mState.Y), new Vector2(mState.X, mState.Y));
                            }



                            //Chọn Target di chuyển Sprite
                            if (mState.RightButton == ButtonState.Pressed)
                            {
                                if (mState.Y <= 535)//nếu click trong vùng màn hình (phía bên trên profile)
                                {
                                    if (bGold)
                                    {
                                        bGold = false;
                                    }
                                    else
                                    {
                                        AClick = false;
                                        cl = Color.Green;
                                        if (!bRightClick && armyFocus.nSprites > 0)
                                        {
                                            for (int i = 0; i < armyFocus.nSprites; i++)
                                            {
                                                if (armyFocus.mySprites[i].Flag == 1)
                                                {
                                                    //Vector2 v = center(new Vector2(mState.X, mState.Y));
                                                    armyFocus.mySprites[i].Target = new Vector2(mState.X, mState.Y);
                                                    //cho b[i, j] = false => ô [i,j] không có ai đứng
                                                    uncheckCell(armyFocus.mySprites[i].PosCenter);
                                                    armyFocus.mySprites[i].FlagAttack = false;
                                                }
                                            }

                                            //Tạo hình target
                                            DefinedTarget(ref bRightClick);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                bRightClick = false;
                            }



                            //Cho Army đang di chuyển
                            soldier.Go(a, b, CellWidth, CellHeight);
                            magic.Go(a, b, CellWidth, CellHeight);

                            //Cho Deadman di chuyển
                            Deadman.Go(a, b, CellWidth, CellHeight);

                            //Update init
                            init.Update(gameTime);

                            //Sản xuất thêm 1 soldier
                            if (kbState.IsKeyDown(Keys.R) && !texting)
                            {
                                RClick = true;
                            }
                            if (kbState.IsKeyUp(Keys.R) && !texting)
                            {
                                if (RClick)
                                    soldier.newArmy(init, mainhome.mySprites[0], 10);
                                RClick = false;
                            }

                            //Sản xuất thêm 1 Deadman
                            if (kbState.IsKeyDown(Keys.T) && !texting)
                            {
                                TClick = true;
                            }
                            if (kbState.IsKeyUp(Keys.T) && !texting)
                            {
                                if (TClick)
                                    Deadman.newArmy(init, mainhome.mySprites[1]);
                                TClick = false;
                            }

                            //Xử lý collision
                            init.TreatCollision(a, b, CellWidth, CellHeight, nCols, nRows);

                            //Sản xuất thêm 1 soldier
                            if (kbState.IsKeyDown(Keys.M) && !texting)
                            {
                                MClick = true;
                            }
                            if (kbState.IsKeyUp(Keys.M) && !texting)
                            {
                                if (MClick)
                                    magic.newArmy(init, mainhome.mySprites[0]);
                                MClick = false;
                            }


                            //Xóa các ô không còn sprite
                            //for (int i = 0; i < rows; i++)
                            //{
                            //    for (int j = 0; j < cols; j++)
                            //    {
                            //        bool flag = false;
                            //        for (int k = 0; k < init.nSprites; k++)
                            //        {
                            //            if (init.mySprites[k].PosCenter == a[i, j] && init.mySprites[k].Life)
                            //            {
                            //                flag = true;
                            //                break;
                            //            }
                            //        }
                            //        if (!flag)
                            //        {
                            //            b[i, j] = false;
                            //        }
                            //    }
                            //}

                            //Xử lý đánh nhau
                            //Attack(soldier, Deadman);
                            //Attack(Deadman, soldier);
                            init.Attack();

                            //Update Sprite Icon
                            spriteIcon.Update();

                            ////update địa hình
                            //for (int i = 0; i < 12; i++)
                            //{
                            //    DiaHinh[i].Update();
                            //}

                            //Giải phóng các sprite đã chết
                            GiaiPhongCacSpriteDaChet();

                        }
                        //nhan Esc
                        if (newState.IsKeyUp(Keys.Escape))
                        {
                            if (EscClick)
                                mCurrentScreen = Screen.Pause;
                            EscClick = false;
                        }

                        if (newState.IsKeyDown(Keys.Escape) /*&& oldState.IsKeyUp(Keys.Escape)*/)
                        {
                            EscClick = true;
                        }
                    }
                    break;
                case Screen.Pause:
                    {
                        KeyboardState newState = Keyboard.GetState();
                        menu.bPause = true;
                        menu.Update(this, gameTime);
                        if (newState.IsKeyDown(Keys.Escape) /*&& oldState.IsKeyUp(Keys.Escape)*/)
                        {
                            EscClick = true;
                        }
                        if (newState.IsKeyUp(Keys.Escape))
                        {
                            if (EscClick)
                                mCurrentScreen = Screen.Main;
                            EscClick = false;
                        }
                    }
                    break;
                default:
                    break;
            }

            base.Update(gameTime);
        }

        private void Tu_Dong_Ra_Linh(int do_kho)
        {
            float n = 1.3f;
            if (do_kho == 1)
                n = 1;
            else
                if (do_kho == 2)
                    n = 0.7f;
            if (realtime <= 10000 * n)
            {

                for (int k = 0; k < deadhome.nSprites; k++)
                {
                    if (realtime % 2000 == 0)
                        for (int i = 0; i < 1; i++)
                        {
                            deadhome.CreateHero(Deadman, deadhome.mySprites[k]);
                        }
                }
            }
            else
            {
                if (realtime <= 40000 * n)
                {
                    for (int k = 0; k < deadhome.nSprites; k++)
                    {
                        if (realtime % 2000 == 0)
                            for (int i = 0; i < 4; i++)
                            {
                                deadhome.CreateHero(Deadman, deadhome.mySprites[k]);
                            }
                    }
                }
                else
                {
                    if (realtime <= 100000 * n)
                    {
                        for (int k = 0; k < deadhome.nSprites; k++)
                        {
                            if (realtime % 1500 == 0)
                                for (int i = 0; i < 10; i++)
                                {
                                    deadhome.CreateHero(Deadman, deadhome.mySprites[k]);
                                }
                        }
                    }
                    else
                    {
                        if (realtime <= 150000 * n)
                        {
                            for (int k = 0; k < deadhome.nSprites; k++)
                            {
                                if (realtime % 1000 == 0)
                                    for (int i = 0; i < 20; i++)
                                    {
                                        deadhome.CreateHero(Deadman, deadhome.mySprites[k]);
                                    }
                            }
                        }
                        else
                        {
                            if (realtime <= 200000 * n)
                            {
                                for (int k = 0; k < deadhome.nSprites; k++)
                                {
                                    if (realtime % 500 == 0)
                                        for (int i = 0; i < 50; i++)
                                        {
                                            deadhome.CreateHero(Deadman, deadhome.mySprites[k]);
                                        }
                                }
                            }
                        }
                    }
                }
            }
        }
        private void DefinedTarget(ref bool bclick)
        {
            bTarget = true;
            sizeTarget = 50;
            vectorTarget = center(new Vector2(mState.X, mState.Y));
            bclick = true;
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            // TODO: Add your drawing code here
            spriteBatch.Begin();

            switch(mCurrentScreen)
            {
                case Screen.Introduction:
                    introduction.Draw(GraphicsDevice, spriteBatch, gameTime);
                    spriteBatch.DrawString(theFont, "Press 'P' to bring up the Menu", new Vector2(10, 600), colorLevel);
                    break;
                case Screen.Menu:
                    menu.Draw(gameTime, GraphicsDevice, spriteBatch);
                    break;
                case Screen.Main:
                    {
                        //Map
                        mapwithcells.Draw(gameTime, spriteBatch);

                        //Draw CircleFocus
                        for (int i = 0; i < armyFocus.nSprites; i++)
                        {
                            if (armyFocus.mySprites[i].Life)
                            {
                                MySprite msp = armyFocus.mySprites[i];
                                int w = CellWidth;
                                int h = 2 * CellHeight / 3;
                                if (msp.TypeMySprite == 6)
                                {
                                    w = w * 3;
                                    h = h * 4;
                                    spriteBatch.Draw(textureCircle, new Rectangle((int)msp.Position.X, (int)msp.Position.Y + CellHeight / 2, w, h), Color.White);
                                }
                                else
                                {
                                    if (msp.TypeMySprite == 7)
                                    {
                                        w = w * 3;
                                        h = (int)(h * 3.5);
                                        spriteBatch.Draw(textureCircle, new Rectangle((int)msp.Position.X - CellWidth/2, (int)msp.Position.Y, w, h), Color.White);
                                    }
                                    else
                                    {
                                        if (msp.TypeMySprite == 1 || msp.TypeMySprite == 3)
                                        {
                                            spriteBatch.Draw(textureCircle, new Rectangle((int)msp.Position.X, (int)msp.Position.Y + CellHeight / 2, w, h), Color.White);
                                        }
                                    }
                                }
                                
                            }
                        }
                        //////Draw init
                        init.Draw(gameTime, spriteBatch);

                        //Draw Building
                        //mainhome.Draw(gameTime, spriteBatch);

                        //Vẽ vùng focus
                        if (Drag)
                        {
                            CreateRectangle(rectFocus);
                        }
                        SpriteFont s = Content.Load<SpriteFont>("SpriteFont1");
                        
                        //spriteBatch.DrawString(s, soldier.mySprites[0].AngleAvoid.ToString(), new Vector2(30, 50), Color.Red);
                        //spriteBatch.DrawString(s, soldier.mySprites[0].AbsX.ToString(), new Vector2(30, 70), Color.Red);
                        //spriteBatch.DrawString(s, soldier.mySprites[0].AbsY.ToString(), new Vector2(30, 90), Color.Red);
                        //spriteBatch.DrawString(s, soldier.mySprites[0].X.ToString(), new Vector2(30, 110), Color.Red);
                        //spriteBatch.DrawString(s, soldier.mySprites[0].DistanceGo.ToString(), new Vector2(30, 130), Color.Red);
                        //spriteBatch.DrawString(s, soldier.nSprites.ToString(), new Vector2(30, 150), Color.Red);
                        spriteBatch.DrawString(s, (new Vector2(mState.X, mState.Y)).ToString(), new Vector2(30, 50), Color.Red);
                        spriteBatch.DrawString(s, gold.ToString(), new Vector2(30, 70), Color.Red);
                        spriteBatch.DrawString(s, "PLAYER: "+ strPlayerName.ToString(), new Vector2(5, 10), Color.Red);


                        //for (int i = 0; i < init.nSprites; i++)
                        //{
                        //    if (init.mySprites[i].Life)
                        //        spriteBatch.DrawString(s, init.mySprites[i].Blood.ToString(), init.mySprites[i].Position, colorLevel);
                        //}
                        //for (int i = 0; i < nRows; i++)
                        //{
                        //    for (int j = 0; j < nCols; j++)
                        //        spriteBatch.DrawString(s, b[i, j].GetHashCode().ToString(), a[i, j], Color.Red);
                        //}


                        DrawProfile();

                        //Draw minimap
                        DrawMiniMap();

                        //Draw Rectangle in MiniMap
                        DrawRectInMiniMap();

                        //Draw Mosue Cursor
                        if (bGold)//Nếu chuẩn bị mua goldbuilding
                        {
                            spriteBatch.Draw(textureIconGoldVirtual, new Rectangle((int)mState.X - CellWidth, (int)mState.Y - CellHeight, CellWidth * 2, CellHeight*2), Color.White);
                        }
                        else
                        {
                            if (AClick)
                                spriteBatch.Draw(TextureCursorAttack, new Rectangle((int)mState.X, (int)mState.Y, 30, 30), Color.White);
                            else
                                spriteBatch.Draw(TextureCursor, new Rectangle((int)mState.X, (int)mState.Y, 30, 30), Color.White);
                        }
                        if (bTarget)
                        {
                            int wt = sizeTarget--;
                            if (wt < 1)
                                bTarget = false;
                            spriteBatch.Draw(TextureCursorTarget, new Rectangle((int)vectorTarget.X  - wt/2, (int)vectorTarget.Y - wt/2, wt, wt), cl);
                        }
                        
                        //Xuất thông báo nếu có
                        if (thongbao != 0)
                        {
                            timeThongbao--;
                            if (timeThongbao < 0)
                                thongbao = 0;
                            String tb = "";
                            switch (thongbao)
                            {
                                case 1: tb = "You are not enough 1000 gold!"; break;
                                case 2: tb = "You are not enough 250 gold!"; break;
                                case 3: tb = "You are not enough 280 gold!"; break;
                                case 4: tb = "You were enough 5 GoldBuilding"; break;
                                case 5: tb = "You were enough 100 hero"; break;
                                default: break;
                            }
                            spriteBatch.DrawString(s, "announcement: " + tb, new Vector2(300, 500), Color.Red); break;
                        }
                        if (mainhome.nSprites < 1)
                        {
                            bKetthuc = true;
                            spriteBatch.DrawString(theFont3, "GAME OVER!!!", new Vector2(VIEWWIDTH/2 - 100, VIEWHEIGHT/2 - 50), Color.Red); break;
                        }
                        if (deadhome.nSprites < 1)
                        {
                            if(!bKetthuc)
                                addHighScore(strPlayerName, realtime / 60);
                            bKetthuc = true;
                            spriteBatch.DrawString(theFont3, "YOU WIN!!!", new Vector2(VIEWWIDTH / 2 - 100, VIEWHEIGHT / 2 - 50), Color.Red); break;
                        }

                        //typing
                        if (texting)
                        {
                            spriteBatch.Draw(textureTextbox, new Rectangle(300, 500, 500, 25), Color.White);
                            if (strText.ToLower().Contains("enter"))
                                strText = strText.Remove(strText.Length - 5, 5);
                            ////if (strText.ToLower().Equals("back"))
                            ////    strText = "";
                            spriteBatch.DrawString(s, strText.ToLower(), new Vector2(303, 502), Color.Red);
                        }
                    }
                    break;
                case Screen.Pause:
                    {
                        menu.Draw(gameTime, GraphicsDevice, spriteBatch);
                        //SpriteFont spriteFont = Content.Load<SpriteFont>("SpriteFont1");
                        //spriteBatch.DrawString(spriteFont, "======> PAUSE <=========", new Vector2(303, 402), Color.Red);
                    }
                    break;
                default:
                    break;
            }

            
            spriteBatch.End();
            base.Draw(gameTime);
        }

        private void DrawProfile()
        {
            spriteBatch.Draw(TextureProfile, new Rectangle(0, VIEWHEIGHT - 164, VIEWWIDTH, 164), Color.White);
            spriteBatch.Draw(TextureDamageArmor, new Vector2(VIEWWIDTH / (2.5f), VIEWHEIGHT-100), Color.White);
            spriteBatch.Draw(TextureRealTime, new Rectangle(VIEWWIDTH - 300, 0, 300, 25), Color.White);
            spriteBatch.DrawString(theFont2, (soldier.nSprites + magic.nSprites).ToString() + "/100", new Vector2(VIEWWIDTH - 160, 5), Color.White);
            spriteBatch.DrawString(theFont2, gold.ToString(), new Vector2(VIEWWIDTH - 255, 5), Color.White);
            spriteBatch.DrawString(theFont2, (realtime/60).ToString(), new Vector2(VIEWWIDTH - 40, 5), Color.Red);
            if (armyFocus.nSprites > 0)
            {
                spriteicon = armyFocus.mySprites[0];
                for (int i = 0; i < armyFocus.nSprites; i++)
                {
                    if (armyFocus.mySprites[i].Level > spriteicon.Level)
                        spriteicon = armyFocus.mySprites[i];
                }
                int x = VIEWWIDTH / 3 - 50;
                if (spriteicon.Score > 0)
                    x -= 15;
                int xb = VIEWWIDTH / 3 - 55;
                if (spriteicon.Blood >= 1000)
                    xb -= 15;
                spriteBatch.DrawString(theFont, spriteicon.Damage.ToString(), new Vector2(VIEWWIDTH / (2.5f) + 85, VIEWHEIGHT - 95), Color.White);
                spriteBatch.DrawString(theFont, spriteicon.Armor.ToString(), new Vector2(VIEWWIDTH / (2.5f) + 85, VIEWHEIGHT - 65), Color.White);
                spriteBatch.DrawString(theFont, spriteicon.Blood.ToString() + "/" + spriteicon.MaxBlood.ToString(), new Vector2(xb, VIEWHEIGHT - 36), Color.Red);
                if (spriteicon.TypeMySprite < 6)
                {
                    spriteBatch.DrawString(theFont, spriteicon.Score.ToString() + "/" + (800 + spriteicon.Level * 200).ToString(), new Vector2(x, VIEWHEIGHT - 22), Color.Yellow);
                    spriteBatch.DrawString(theFont, "level:", new Vector2(VIEWWIDTH / (2.5f) + 150, VIEWHEIGHT - 95), Color.White);
                    spriteBatch.DrawString(theFont, spriteicon.Level.ToString(), new Vector2(VIEWWIDTH / (2.5f) + 230, VIEWHEIGHT - 95), Color.Yellow);
                }
                //hình icon đại diện
                if (spriteicon.TypeMySprite == 1)
                {
                    spriteIcon = spriteIconHero;
                    spriteBatch.Draw(TextureAttack, new Rectangle(VIEWWIDTH - 253, VIEWHEIGHT - 132, 57, 38), Color.White);
                    //spriteBatch.Draw(TextureMove, new Rectangle(VIEWWIDTH - 70, VIEWHEIGHT - 132, 57, 38), Color.White);
                }
                else
                {
                    if (spriteicon.TypeMySprite == 6)
                    {
                        spriteIcon = spriteIconBarrack;
                        spriteBatch.Draw(textureIconHero, new Rectangle(VIEWWIDTH - 246, VIEWHEIGHT - 134, 41, 39), Color.White);
                        spriteBatch.Draw(textureIconMagic, new Rectangle(VIEWWIDTH - 186, VIEWHEIGHT - 134, 41, 39), Color.White);
                        spriteBatch.Draw(textureIconGold, new Rectangle(VIEWWIDTH - 246, VIEWHEIGHT - 90, 41, 39), Color.White);
                    }
                    else
                    {
                        if (spriteicon.TypeMySprite == 3)
                        {
                            spriteBatch.Draw(TextureAttack, new Rectangle(VIEWWIDTH - 253, VIEWHEIGHT - 132, 57, 38), Color.White);
                            spriteIcon = spriteIconMagic;
                        }
                        else
                        {
                            if (spriteicon.TypeMySprite == 7)
                            {
                                //spriteBatch.Draw(TextureAttack, new Rectangle(VIEWWIDTH - 253, VIEWHEIGHT - 132, 57, 38), Color.White);
                                spriteIcon = spriteIconGoldBuilding;
                            }
                        }
                    }
                }
                spriteIcon.Draw(spriteBatch, spriteicon.Flag);
            }
        }
        private Vector2 Map2MiniMap(Vector2 pos)
        {
            int w = 13 + (int)((float)(pos.X - mapwithcells.Topleft.X) * (float)WidthMiniMap / WidthMap);
            int h = 532 + (int)(((float)pos.Y - mapwithcells.Topleft.Y) * (float)HeighMiniMap / HeighMap);
            return new Vector2(w, h);
        }
        private void DrawRectInMiniMap()
        {
            Vector2 v = Map2MiniMap(new Vector2(0, 0));
            int w = (int)(VIEWWIDTH * WidthMiniMap / WidthMap);
            int h = (int)(VIEWHEIGHT * HeighMiniMap / HeighMap);
            Rectangle rect = new Rectangle((int)v.X, (int)v.Y, w, h);
            CreateRectangle(rect);
        }
        private void SearchMiniMap()
        {
            Vector2 miniLocal = new Vector2(mState.X - 13, mState.Y - 532);
            int w = (int)((float)miniLocal.X * (float)WidthMap / WidthMiniMap);
            int h = (int)((float)miniLocal.Y * (float)HeighMap / HeighMiniMap);
            Vector2 realpos = new Vector2(w, h);
            Vector2 zero = mapwithcells.Topleft;
            Vector2 v = zero + realpos;
            mapwithcells.MoveMap(v);
        }
        public void DrawMiniMap()
        {
            spriteBatch.Draw(TextureMiniMap, new Rectangle(13, 532, WidthMiniMap, HeighMiniMap), Color.White);
            int w = 0;
            int h = 0;
            for (int i = 0; i < init.nSprites; i++)
            {
                MySprite ms = init.mySprites[i];
                Vector2 pos = ms.Position;
                Vector2 v = Map2MiniMap(pos);
                w = (int)v.X;
                h = (int)v.Y;
                Color cl;
                if (ms.Flag == 1)
                {
                    cl = Color.Green;
                }
                else
                {
                    cl = Color.Red;
                }
                if (ms.TypeMySprite < 6)
                {
                    spriteBatch.Draw(TextureLocal, new Rectangle(w, h, 3, 3), cl);
                }
                else
                {
                    if(ms.TypeMySprite == 6)
                        spriteBatch.Draw(TextureLocal, new Rectangle(w, h, 9, 9), cl);
                    else
                    {
                        if (ms.TypeMySprite == 7)
                            spriteBatch.Draw(TextureLocal, new Rectangle(w, h, 6, 6), cl);
                    }
                }
            }
        }
        private void XulyProfileBarrack(Vector2 vt)
        {
            if ((853 < vt.X) && (896 > vt.X) &&
                    (552 < vt.Y) && (581 > vt.Y))
            {
                if (gold >= 250)
                {
                    if (soldier.nSprites + magic.nSprites < 100)
                    {
                        gold -= 250;
                        //soldier.newArmy(init);
                        mainhome.CreateHero(soldier, mainhome.mySprites[0]);
                    }
                    else
                    {
                        BatThongBao(5);
                    }
                }
                else
                {
                    BatThongBao(2);
                }
            }
            else
            {
                if ((910 < vt.X) && (958 > vt.X) &&
                    (552 < vt.Y) && (581 > vt.Y))
                {
                    if(gold >= 280)
                    {
                        if (soldier.nSprites + magic.nSprites < 100)
                        {
                            gold -= 280;
                            //magic.newArmy(init);
                            mainhome.CreateHero(magic, mainhome.mySprites[0]);
                        }
                        else
                        {
                            BatThongBao(5);
                        }
                    }
                    else
                    {
                        BatThongBao(3);
                    }
                }
                else
                {
                    if ((308 < vt.X) && (385 > vt.X) &&
                    (583 < vt.Y) && (636 > vt.Y))
                    {
                        SearchByIcon();
                    }
                    else
                    {
                        if ((852 < vt.X) && (896 > vt.X) &&
                        (593 < vt.Y) && (625 > vt.Y))
                        {
                            if (gold >= 1000)
                            {
                                if (goldbuilding.nSprites < 5)
                                {
                                    gold -= 1000;
                                    bGold = true;
                                }
                                else
                                {
                                    BatThongBao(4);//thông báo đã đủ 5 nhà vàng
                                }
                            }
                            else
                            {
                                BatThongBao(1); //thông báo không đủ 1000 tiền
                            }
                        }
                    }
                }
            }
        }
        private void BatThongBao(int i)
        {
            thongbao = i;
            timeThongbao = 300;
        }
        private void XulyProfileSoldier(Vector2 vt)
        {
            if ((853 < vt.X) && (896 > vt.X) &&
                    (552 < vt.Y) && (581 > vt.Y))
            {
                AClick = true;
                cl = Color.Red;
            }
            else
            {
                if ((308 < vt.X) && (385 > vt.X) &&
                    (583 < vt.Y) && (636 > vt.Y))
                {
                    SearchByIcon();
                }
            }
        }
        private void XulyProfileGoldBuilding(Vector2 vt)
        {
            if ((308 < vt.X) && (385 > vt.X) &&
            (583 < vt.Y) && (636 > vt.Y))
            {
                SearchByIcon();
            }
        }
        private void SearchByIcon()
        {
            mapwithcells.MoveMap(spriteicon.PosCenter);
        }

        //Tạo vùng Focus
        private Rectangle CreateRect(Vector2 v1, Vector2 v2)
        {
            int x = Math.Min((int)v1.X, (int)v2.X);
            int y = Math.Min((int)v1.Y, (int)v2.Y);
            int w = (int)Math.Abs(v1.X - v2.X);
            int h = (int)Math.Abs(v1.Y - v2.Y);
            Rectangle rec = new Rectangle(x, y, w, h);
            return rec;
        }


        private void CreateRectangle(Rectangle rectfocus)
        {
            Vector2 pos = new Vector2(rectfocus.Left, rectfocus.Top);
            int width = rectfocus.Width;
            int height = rectfocus.Height;
            if (width > 0 && height > 0)
            {
                Texture2D rect = new Texture2D(graphics.GraphicsDevice, width, height);
                int total = width * height;
                Color[] data = new Color[total];
                for (int i = 0; i < data.Length; ++i)
                {
                    if ((i >= 0 && i < width) || (i >= (total - width) && i < total) || (i % width == 0) || (i % width == (width - 1)))
                        data[i] = Color.Chocolate;
                }
                rect.SetData(data);
                spriteBatch.Draw(rect, pos, Color.Red);
            }
        }

        static public Vector2 center(Vector2 vt)
        {
            Vector2 v = vt - mapwithcells.Topleft;
            int x = (int)v.X;
            int y = (int)v.Y;
            x = x / CellWidth;
            y = y / CellHeight;
            if (x >= 0 && x < nCols && y >= 0 && y < nRows)
            {
                return a[y, x];
            }
            else
                return vt;
        }

        static public void uncheckCell(Vector2 vt)
        {
            Vector2 v = vt - mapwithcells.Topleft;
            int x = (int)v.X;
            int y = (int)v.Y;
            x = x / CellWidth;
            y = y / CellHeight;
            if (x >= 0 && x < nCols && y >= 0 && y < nRows)
                b[y, x] = false;
        }

        static public bool TestVector(Vector2 vt)
        {
            Vector2 vtt = vt - Game1.mapwithcells.Topleft;
            Vector2 v = center(vtt);
            int x = (int)v.X;
            int y = (int)v.Y;
            x = x / CellWidth;
            y = y / CellHeight;
            if (x >= 0 && x < nCols && y >= 0 && y < nRows)
                return b[y, x];
            return false;
        }

        static public Vector2 LocalCell(Vector2 vtt)//trả về số thứ tự ô
        {
            Vector2 v = vtt - Game1.mapwithcells.Topleft;
            //v = center(v);
            int x = (int)v.X;
            int y = (int)v.Y;
            x = x / CellWidth;
            y = y / CellHeight;
            if (x >= 0 && x < nCols && y >= 0 && y < nRows)
                return new Vector2(x, y);
            return new Vector2();
        }

        static public int Dis_Soldier_Deadman(Vector2 v1, Vector2 v2)
        {
            int d = (int)(v1 - v2).Length();
            return d;
        }


        public void GiaiPhongCacSpriteDaChet()
        {
            soldier.SapXepObject();
            Deadman.SapXepObject();
            mainhome.SapXepObject();
            deadhome.SapXepObject();
            armyFocus.SapXepObject();
            init.SapXepObject();
        }

        //Delegate, event Menu
        void menu_easy()
        {
            bPause = false;
            mCurrentScreen = Screen.Main;
            colorLevel = Color.White;
            Do_Kho = 0;
        }

        void menu_normal()
        {
            mCurrentScreen = Screen.Main;
            colorLevel = Color.Yellow;
            Do_Kho = 1;
        }
        void menu_hard()
        {
            mCurrentScreen = Screen.Main;
            colorLevel = Color.Red;
            Do_Kho = 2;
        }

        void menu_onSound()
        {
            MediaPlayer.Stop();
            MediaPlayer.Play(song);
            doingsound = true;
        }

        void menu_offSound()
        {
            //
            MediaPlayer.Stop();
            doingsound = false;
        }

        void menu_quitmission()
        {
            //Doing something
            Do_Kho = -1;
            realtime = 0;
            mCurrentScreen = Screen.Menu;
        }

        public void creatXMLfile()
        {
            XmlTextWriter wr = new XmlTextWriter("highscore.xml", Encoding.UTF8);
            wr.Formatting = Formatting.Indented;
            wr.WriteStartElement("TOP_TEN");
            wr.WriteEndElement();
            wr.Close();
        }

        public void addHighScore(String strname, int time)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("highscore.xml");
            XmlElement topten = doc.DocumentElement;
            int n = topten.ChildNodes.Count;
            if (n >= 10)
            {
                XmlNode Minuser = topten.ChildNodes[0]; 
                for (int i = 0; i < n; i++)//tim user zom nhat
                {
                    XmlNode user = topten.ChildNodes[i];
                    int score = Convert.ToInt32(user.Attributes["Score"].Value.ToString());
                    if (Convert.ToInt32(Minuser.Attributes["Score"].Value.ToString()) < Convert.ToInt32(user.Attributes["Score"].Value.ToString()))
                    {
                        Minuser = user;
                    }
                }

                if (time < Convert.ToInt32(Minuser.Attributes["Score"].Value.ToString()))
                {
                    Minuser.ParentNode.RemoveChild(Minuser);//xoa 1 user zom nhat

                    XmlElement newuser = doc.CreateElement("USER");
                    newuser.SetAttribute("Name", strname);
                    newuser.SetAttribute("Score", time.ToString());
                    topten.AppendChild(newuser);
                }
            }
            if (n < 10)
            {
                XmlElement newuser = doc.CreateElement("USER");
                newuser.SetAttribute("Name", strname);
                newuser.SetAttribute("Score", time.ToString());
                topten.AppendChild(newuser);            
            }
            doc.Save("highscore.xml");
        }
    }
}
